﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace TSharp.Core.Unity
{
	/// <summary>
	/// 配置文件获取
	/// <para>by tangjingbo at 2010-1-8 16:27</para>
	/// </summary>
	public static class WebConfigUtil
	{
		/// <summary>
		/// 获取外部配置文件
		/// </summary>
		/// <param name="appkeyOrFileName">web.config 中AppSettings的key或者配置文件名称</param>
		/// <returns></returns>
		public static FileConfigurationSource Get(string appkeyOrFileName)
		{
			string aopcfg = ConfigurationManager.AppSettings.Get(appkeyOrFileName);
			if (string.IsNullOrEmpty(aopcfg))
			{
				aopcfg = appkeyOrFileName + ".config";
			}
			string cfgfile = null;
			cfgfile = aopcfg.StartsWith("~/")
			          	? HttpContext.Current.Server.MapPath(aopcfg)
			          	: Path.Combine(AppDomain.CurrentDomain.BaseDirectory, aopcfg);
			if (File.Exists(cfgfile))
				return new FileConfigurationSource(cfgfile);
			throw new FileNotFoundException(string.Format("‘{0}’配置文件不存在", cfgfile));
		}

		/// <summary>
		/// 获取默认配置文件Selction节点的配置
		/// </summary>
		/// <typeparam name="TSection">The type of the section.</typeparam>
		/// <param name="sectionName">The section.</param>
		/// <returns></returns>
		public static TSection GetSection<TSection>(string sectionName) where TSection : ConfigurationSection
		{
			return ConfigurationManager.GetSection(sectionName) as TSection;
		}
	}
}